package com.example.mywechat;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.mywechat.adapter.ChatListAdapter;
import com.example.mywechat.model.ChatListModel;
import com.example.mywechat.model.Forecast;
import com.example.mywechat.util.ChatListDataBaseHelper;
import com.example.mywechat.util.MsgDataBaseHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
//继承BaseActivity后,会调用BaseActivity 注册接收器
public class MainActivity extends BaseActivity {
    RadioGroup tab;
    ListView listView;
    List<ChatListModel> myListData = new ArrayList<>();
    ChatListDataBaseHelper chatListDataBaseHelper;
    MsgDataBaseHelper msgDataBaseHelper;
    TextView tv;
    int tem;
    URL url ;
    Handler myHandler = new Handler(){
        public void handleMessage(@NonNull Message msg) {
            if(msg.what==0x100){
                String jsonStr = (String)msg.obj;
                JsonToWeather(jsonStr);
                System.out.println(jsonStr);
            }
            super.handleMessage(msg);
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chatListDataBaseHelper = new ChatListDataBaseHelper(this, "Message", null, 3);
        msgDataBaseHelper = new MsgDataBaseHelper(this,"MessageInfo1",null,3);
        //insertData();
        initData();
        listView = findViewById(R.id.listView);
        tab = findViewById(R.id.tabs_rg);
        final ChatListAdapter adapter = new ChatListAdapter(this,R.layout.item,myListData);
        listView.setAdapter(adapter);
        try {
            url = new URL("http://wthrcdn.etouch.cn/weather_mini?city=佛山");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String strName = myListData.get(i).getName();
                View view1 = adapterView.getChildAt(i);//获取适配器中的被点击控件
                tv = (TextView) view1.findViewById(R.id.message);//获取被点击控件中的子控件id
                tem = i;
                //tv.setText(searchLastMessage());//设置最近一条消息
                if (view.getId() == view1.findViewById(R.id.headImage).getId())
                    Toast.makeText(getApplicationContext(), "您点击了+"+strName+"头像", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(getApplicationContext(),"您想与"+strName+"聊天",Toast.LENGTH_SHORT).show();

                startActivity(new Intent(getApplicationContext(), MsgActivity.class).putExtra("chatFriendName",strName).putExtra("tem",tem));
                finish();
            }
        });

        //设置不同的监听事件，防止天气预报页面点击item报错。
        tab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.message_tab:listView.setAdapter(adapter);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                String strName = myListData.get(i).getName();
                                View view1 = adapterView.getChildAt(i);//获取适配器中的被点击控件
                                tv = (TextView) view1.findViewById(R.id.message);//获取被点击控件中的子控件id
                                tem = i;
                                //tv.setText(searchLastMessage());//设置最近一条消息
                                if (view.getId() == view1.findViewById(R.id.headImage).getId())
                                    Toast.makeText(getApplicationContext(), "您点击了+"+strName+"头像", Toast.LENGTH_SHORT).show();
                                else
                                    Toast.makeText(getApplicationContext(),"您想与"+strName+"聊天",Toast.LENGTH_SHORT).show();

                                startActivity(new Intent(getApplicationContext(), MsgActivity.class).putExtra("chatFriendName",strName).putExtra("tem",tem));
                                finish();
                            }
                        });
                    break;
                    case R.id.forecast_tab:new WeatherThread(url).start();
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                        }
                    });
                    break;
                }
            }
        });
        /*
        * 原本一直想通过获取listview的子控件来更新最近一条消息，尝试了很多方法，都获取不到子控件。
        * 后面转变一下思路，更改数组内容就好了。
        * */
        if(getIntent().getStringExtra("lastMsg")!=null){
            myListData.get(getIntent().getIntExtra("tem",1)).setMessage(getIntent().getStringExtra("lastMsg"));
            listView.invalidate();
        }

    }

    private void insertData(){
        //用于刚建表时插入数据
        SQLiteDatabase db = chatListDataBaseHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("imgHeadId", R.drawable.tencent);
        values.put("friendName", "腾讯新闻");
        values.put("msg", "震惊！！！");
        values.put("date", "12:00");
        db.insert("Message", null, values);
        values.clear();
    }
    private void initData() {
        /*String[] name = new String[]{
                "小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆","小汤姆"
        };
        String[] message = new String[]{
                "Hello", "Hello", "Hello", "Hello", "Hello", "Hello", "Hello", "Hello","Hello", "Hello", "Hello", "Hello", "Hello", "Hello", "Hello", "Hello"
        };
        int[] headImage = new int[]{
          R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head,R.drawable.head
        };
        for(int i = 0;i<name.length;i++){
            ChatListModel chatList = new ChatListModel(name[i],message[i],headImage[i]);
            myListData.add(chatList);
        }
        */
        SQLiteDatabase db = chatListDataBaseHelper.getWritableDatabase();
        Cursor cursor = db.query("Message", null, null, null, null, null, null);
        cursor.moveToFirst();
        for (int i = 1; i <= cursor.getCount(); i++) {//数据库遍历
            int imgHeadId = Integer.parseInt(cursor.getString(cursor.getColumnIndex("imgHeadId")));
            String friendName = cursor.getString(cursor.getColumnIndex("friendName"));
            String msg = cursor.getString(cursor.getColumnIndex("msg"));
            String date = cursor.getString(cursor.getColumnIndex("date"));
            ChatListModel chatList = new ChatListModel(friendName,msg,imgHeadId,date);
            myListData.add(chatList);
            cursor.moveToNext();
        }
    }
    class WeatherThread extends  Thread{
        URL myUrl;
        private ArrayList JsonToWeather(String jsonStr) {
            ArrayList list = null;
            try {
                //把字符串转换为jsonObj
                JSONObject jsonObject = new JSONObject(jsonStr);
                String jsonData = jsonObject.getString("data");
                Gson gson = new Gson();
                //解析接下来五天的天气预报
                JSONObject jsonObjectNext = new JSONObject(jsonData);
                String jsonStrForecast = jsonObjectNext.getString("forecast");
                list = gson.fromJson(jsonStrForecast, new TypeToken<List<Forecast>>() {
                }.getType());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return list;
        }
        public WeatherThread(URL myUrl) {
            this.myUrl = myUrl;
        }

        @Override
        public void run() {
            try {
                HttpURLConnection conn= (HttpURLConnection) myUrl.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);
                int conde = conn.getResponseCode();
                if(conde == 200){
                    InputStream in = conn.getInputStream();
                    BufferedReader reader = null;
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuffer response = new StringBuffer();
                    String line;
                    //line = reader.readLine();
                    while((line = reader.readLine()) != null){
                        response.append(line);
                        Message msg = new Message();
                        msg.what = 0x100;
                        msg.obj = response.toString();
                        myHandler.sendMessage(msg);
                    }
                }else {
                    Message msg = new Message();
                    msg.what = 0x101;
                    myHandler.sendMessage(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            super.run();
        }
    }
    private void JsonToWeather(String jsonStr){
        try {
            //把字符串转换为jsonObj
            JSONObject jsonObject = new JSONObject(jsonStr);
            //解析当前的天气
            String jsonData = jsonObject.getString("data");
            Gson gson = new Gson();
            //解析接下来五天的天气预报
            JSONObject jsonObjectNext = new JSONObject(jsonData);
            String jsonStrForecast = jsonObjectNext.getString("forecast");
            ArrayList list = gson.fromJson(jsonStrForecast, new TypeToken<List<Forecast>>(){}.getType());
            //定义适配器
            ArrayAdapter forecastAdp = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1,list);
            listView.setAdapter(forecastAdp);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
